package example.quartz;

import java.text.ParseException;
import java.util.Date;

import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;

public class ScanDirectoryJob implements Job {

	private static ScanDirectoryJob directoryJob;
	private static long min=2;
	private static Scheduler scheduler;
	
	public static void main(String[] args) throws ParseException {

		try {
			// Create a Scheduler and schedule the Job
			directoryJob = new ScanDirectoryJob();
			scheduler = directoryJob.createScheduler();
			directoryJob.scheduleJob(scheduler);
			// Start the Scheduler running
			scheduler.start();

		} catch (SchedulerException ex) {
		}
	}

	public Scheduler createScheduler() throws SchedulerException {
		return StdSchedulerFactory.getDefaultScheduler();
	}

	private void scheduleJob(Scheduler scheduler) throws SchedulerException, ParseException {
		System.out.println("HORA DE INICIO: " + (new Date()) );
		// Create a JobDetail for the Job
		JobDetail jobDetail = new JobDetail("EJECUCION EXPONENCIAL BINARIA",Scheduler.DEFAULT_GROUP, ScanDirectoryJob.class);
		// Create a trigger that fires every 10 seconds, forever
		
		Trigger trigger = new CronTrigger("CronTrigger", null, "0 0/" +min+" * * * ?");
//		trigger.setName("scanTrigger");
//		// Start the trigger firing from now
//		trigger.setStartTime(new Date());
		// Associate the trigger with the job in the scheduler
		scheduler.scheduleJob(jobDetail, trigger);
		min= (long) Math.pow(min,2);
	}

	public void execute(JobExecutionContext context)throws JobExecutionException {
		System.out.println("TIEMPO DE CRON " + min);
		System.out.println("HOLA CHAVON: " + (new Date()) );
		try {
			scheduler.shutdown();
			scheduler = directoryJob.createScheduler();
			directoryJob.scheduleJob(scheduler);
			scheduler.start();
		} catch (SchedulerException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
	}
}
